#include <cctype>
#include <sstream>
#include "StaticNextBNF.h"
#include "MyString.h"

StaticNextBNF::StaticNextBNF(std::map<std::string, std::string> const & var)
{
  this->_pars["HAI"] = &StaticNextBNF::hai;
  this->_pars["VISIBLE"] = &StaticNextBNF::visible;
  this->_pars["KTHXBYE"] = &StaticNextBNF::kthxbye;
  this->_pars["BTW"] = &StaticNextBNF::btw;
  this->_pars["CAN HAS"] = &StaticNextBNF::canhas;
  this->_pars["I HAS A"] = &StaticNextBNF::ihasa;
  this->_pars["LOL"] = &StaticNextBNF::lol;
  this->_var = var;
}

std::string		StaticNextBNF::visible(std::string line)
{
  MyString::trim(line);
  if (line[0] != '"' || line[line.size() - 1] != '"')
    return ("");
  return ("\tstd::cout << " + line +  " << std::endl;");
}

std::string		StaticNextBNF::btw(std::string line)
{
  return ("//" + line.substr(line.find(" ")));
}

std::string		StaticNextBNF::canhas(std::string)
{
  std::ostringstream		re;

  re << "#include <iostream>" << std::endl;
  return (re.str());
}

std::string		StaticNextBNF::hai(std::string line)
{
  MyString::trim(line);
  if (line != "")
    return ("");
  return ("int\t\tmain()\n{");
}

std::string		StaticNextBNF::ihasa(std::string line)
{
  MyString::trim(line);
  return ("\t" + this->_var[line] + line + ";");
}

std::string		StaticNextBNF::lol(std::string line)
{ 
  MyString::trim(line);
  std::string		var = line.substr(0, line.find(" "));
  MyString::trim(var);
  std::string		r = line.substr(var.size(), line.find(" ", var.size()));
  MyString::trim(r);
  std::string		val = line.substr(line.find_last_of(" "));

  std::cout << var << " " << r << " " << val << std::endl;
  if (r != "R" || val == "")
    return ("");
  return ("\t" + var + "= " + val + ";");
}

std::string		StaticNextBNF::kthxbye(std::string line)
{
  MyString::trim(line);
  if (line != "")
    return ("");
  return ("\treturn (0);\n}");
}

std::string		StaticNextBNF::translate(std::string line)
{
  std::map<std::string, func >::iterator          itb = this->_pars.begin();
  std::map<std::string, func >::iterator          ite = this->_pars.end();

  for (; itb != ite; ++itb)
    {
      if (!line.find((*itb).first))
	return (this->*(itb->second))(line.substr((*itb).first.length()));
    }
  return ("");
}

bool			StaticNextBNF::priority(std::string line)
{
  if (!line.compare(0, 3,"IZ ") || !line.compare(0, 9, "IM IN YR ")
      || !line.compare(0, 6, "NOWAI  ") || !line.compare(0, 6, "YARLY "))
    return (true);
  return (false);
}
